package com.imooc.seckill.config;

import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * \* @author: bear
 * \* Date: 2021-07-30-15:26
 * \* describe:
 */
@Slf4j
@Component
public class RedisLock {

	@Autowired
	private StringRedisTemplate redisTemplate;
	public static final String key = "redis_key";

	/**
	 * @param value 当前时间+超时时间
	 * @param key
	 * @param value
	 * @return
	 */
	public boolean trylock(String value){
		if(redisTemplate.opsForValue().setIfAbsent(key,value)){
			log.debug("此时已获取锁");
			return true;
		}
		String lockAvalue = redisTemplate.opsForValue().get(key);
		if(!StringUtils.isEmpty(lockAvalue) && Long.parseLong(lockAvalue) < System.currentTimeMillis()){
			//key的值不为空，且，获取的值小于当前时间，可以理解为失效
			String getsetValue =  redisTemplate.opsForValue().getAndSet(key,value);
			if(StringUtils.isEmpty(getsetValue) ||
					(!StringUtils.isEmpty(getsetValue) && getsetValue.equals(lockAvalue))){
				return true;
			}
		}
		return false;
	}

	public void unlock(String value){
		try{
			String current = redisTemplate.opsForValue().get(key);
			if(!StringUtils.isEmpty(current) && current.equals(value)){
				redisTemplate.opsForValue().getOperations().delete(key);
			}
		}catch (Exception e){
			log.error("解锁异常={}",e);
		}
	}
}
